package com.qls.ali.biz.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qls.ali.biz.data.util.FzUtil;
import com.qls.ali.biz.order.entity.OrderEntity;
import com.qls.ali.biz.order.service.biz.OrderNotice;
import com.qls.ali.biz.order.service.biz.ReceOrderService;
import com.qls.ali.biz.order.service.mybatis.DtStoreService;
import com.qls.ali.biz.order.service.mybatis.OrderService;
import com.qls.ali.biz.order.util.OrderConstant;
import com.qls.core.ali.order.deligoods.request.DeliGoods;
import com.qls.core.entity.DtStore;
import com.qls.core.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

/**
 * 飞猪订单接入
 *
 * @author doyoung
 */
@Slf4j
@RestController
public class OrderController {

    @Autowired
    private OrderNotice orderNotice;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DtStoreService dtStoreService;

    @Autowired
    private ReceOrderService receOrderService;

    /**
     * 阿里订单通知接口
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @throws IOException IOException
     */
    @RequestMapping("order/notice")
    public void aliOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String postXmlData = sb.toString();
        String result = orderNotice.router(postXmlData);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(result);
    }

    /**
     * 下单渠道回调通知
     *
     * @param data JSONObject
     * @return R
     */
    @RequestMapping(value = "order/callback", method = RequestMethod.POST)
    public R callback(@RequestBody JSONObject data) {
        log.info("美团预定后回调通知:{}", data);
        String buyOrderId = data.getString("buyOrderId");
        int code = data.getInteger("code");
        OrderEntity orderEntity = orderService.getBaseMapper().selectOne(new QueryWrapper<OrderEntity>().eq("buy_order_id", buyOrderId));
        if(Objects.isNull(orderEntity)) {
            log.warn("购买渠道订单号：{}，数据库不存在此订单", buyOrderId);
            return R.error();
        }
        DtStore dtStore = dtStoreService.getById(orderEntity.getDtStoreId());
        DeliGoods deliGoods = new DeliGoods();
        deliGoods.setTid(orderEntity.getOrderCode());
        // 0预定成功 -1预定失败  1取消成功 2客服介入退款 3已入住
        switch (code) {
            // 预定成功
            case 0:
                deliGoods.setOptType(OrderConstant.AliOrderUpdateStatus.Confirm.getValue());
                orderEntity.setBuyStatus(OrderConstant.MtLocalOrdBuyStatus.Purchased.getValue());
                orderEntity.setOrderStatus(OrderConstant.AliLocalOrderStatus.Delivered.getValue());
                log.info("通知更新飞猪订单，预定成功，订单号：{}", buyOrderId);
                break;
            //预定失败
            case -1:
                deliGoods.setOptType(OrderConstant.AliOrderUpdateStatus.NonConfirm.getValue());
                orderEntity.setBuyStatus(OrderConstant.MtLocalOrdBuyStatus.Purchfailure.getValue());
                log.info("通知更新飞猪订单，预定失败，订单号：{}", buyOrderId);
                break;
            // 取消成功
            case 1:
                orderEntity.setBuyStatus(OrderConstant.MtLocalOrdBuyStatus.Canceled.getValue());
                log.info("通知更新飞猪订单，订单取消成功，订单号：{}", buyOrderId);
                return R.ok();
            // 客服介入退款
            case 2:
                orderEntity.setBuyStatus(OrderConstant.MtLocalOrdBuyStatus.Chargebacked.getValue());
                log.info("通知更新飞猪订单，客服介入退款，订单号：{}", buyOrderId);
                return R.ok();
            // 已入住
            case 3:
                deliGoods.setOptType(OrderConstant.AliOrderUpdateStatus.CheckIn.getValue());
                orderEntity.setBuyStatus(OrderConstant.MtLocalOrdBuyStatus.CheckIn.getValue());
                orderEntity.setOrderStatus(OrderConstant.AliLocalOrderStatus.CheckIn.getValue());
                log.info("通知更新飞猪订单，已入住，订单号：{}", buyOrderId);
                break;
            default:
                log.info("通知更新飞猪订单，未知");
                break;
        }
        String result = FzUtil.order(deliGoods, dtStore.getAppKey(), dtStore.getSessionKey(), dtStore.getSecret());
        log.info("更新飞猪订单，订单号：{}，返回结果：{}", orderEntity.getOrderCode(), result);
        orderService.updateById(orderEntity);
        return R.ok();
    }

    @RequestMapping(value = "order/buy", method = RequestMethod.GET)
    public R buy(@RequestParam Map<String, Object> map) {
        Integer id = Integer.valueOf(map.get("id").toString());
        return receOrderService.manuBook(id);
    }

}
